package com.zg.common.core.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
@Slf4j
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> T getBean(String beanName) {
        return (T) applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

//    public static Object getBeanByClass(Class clazz) {
//        return applicationContext.getBean(clazz);
//    }

    public static boolean containsBean(String requiredType) {
        return applicationContext.containsBean(requiredType);
    }

    public static <T> List<T> getBeanOfType(Class<T> requiredType) {
        Map<String, T> map = applicationContext.getBeansOfType(requiredType);
        return map == null ? null : new ArrayList<>(map.values());
    }
//    public static void autowireBean(Object bean) {
//        applicationContext.getAutowireCapableBeanFactory().autowireBean(bean);
//    }
//
//    public static void registerSingleton(Object bean, String name) {
//        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
//        BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name);
//        if (beanFactory.containsBeanDefinition(name)) {
//            beanFactory.removeBeanDefinition(name);
//        }
//        beanDefinition.setBeanClassName(bean.getClass().getCanonicalName());
//        beanFactory.registerBeanDefinition(name, beanDefinition);
//        beanFactory.registerSingleton(name, bean);
//    }
}
